package com.example.applets.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.applets.entity.Address;
import com.example.applets.entity.Product;
import com.example.applets.service.impl.AddressServiceImpl;
import com.example.applets.service.impl.ProductServiceImpl;
import com.example.applets.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 商品 前端控制器
 * </p>
 *
 * @author 云烟成雨丶
 * @since 2020-10-09
 */
@Controller
@RequestMapping("/applets/product")
public class ProductController {
    @Autowired
    private ProductServiceImpl productService;

    @Autowired
    private AddressServiceImpl addressService;

    @RequestMapping("/page")
    @ResponseBody
    //分页
    public AjaxResult selectPage(@RequestParam("spu") String spu, @RequestParam("sku") String sku, @RequestParam("order") int order, @RequestParam("ord") String ord, @RequestParam("pname") String pname, @RequestParam(value = "inuse", required = false) String inuse, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        //   System.out.println("信息内容为" + order + "和" + ord);
        //分页
        Page<Product> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        //条件构造器
        if (!spu.equals(""))
            wrapper.like("spu", spu);
        if (!sku.equals(""))
            wrapper.like("sku", sku);
        if (!pname.equals(""))
            wrapper.like("name", pname);
        if (!inuse.equals(""))
            wrapper.eq("inuse", inuse.equals("1") ? true : false);
        if (order == 1) {
            wrapper.orderByAsc(ord);
        } else if (order == 0) {
            wrapper.orderByDesc(ord);
        }
        wrapper.eq("inuse", true);
        //获得集合
        List<Product> list = productService.page(page, wrapper).getRecords();
        //获得页数
        int num = (productService.count(wrapper) - 1) / pageSize + 1;
        //map集合
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", list);
        map.put("total", num);
        if (list.size() == 0)
            return AjaxResult.error("暂无数据");
        return AjaxResult.success(map);
    }

    @RequestMapping("/delete")
    @ResponseBody
    //逻辑删除
    public AjaxResult deleteProduct(@RequestParam("id") long id) {
        Product product = productService.getById(id);
        product.setInuse(false);
        if (!productService.updateById(product))
            return AjaxResult.error("删除失败!");
        return AjaxResult.success("删除成功!");
    }

    @RequestMapping("/add")
    @ResponseBody
    //商品增加
    public AjaxResult addProduct(@RequestParam(required = false, value = "simgs") MultipartFile pic, Product product) throws IOException {
        if (!pic.isEmpty()) {
            //起新名字
            String oldName = pic.getOriginalFilename();
            String prefix = oldName.substring(oldName.lastIndexOf('.'));
            String newName = UUID.randomUUID() + prefix;
            product.setImgs(newName);
            //确定路径
            String path = "F://picture//";
            //修改存储路径
            pic.transferTo(new File(path, newName));
        }
        if (!productService.save(product))
            return AjaxResult.error("保存失败!");
        return AjaxResult.success("保存成功!");
    }

    @RequestMapping("/select")
    //查找单个
    public String selectProduct(@RequestParam("id") long id, Model model) {
        Product product = productService.getById(id);
        model.addAttribute("p", product);
        return "kProduct/UpdateProduct";
    }

    @RequestMapping("/update")
    @ResponseBody
    //修改产品
    public AjaxResult updateProduct(@RequestParam(required = false, value = "simgs") MultipartFile pic, Product product) throws IOException {
        if (!pic.isEmpty()) {
            //起新名字
            String oldName = pic.getOriginalFilename();
            String prefix = oldName.substring(oldName.lastIndexOf('.'));
            String newName = UUID.randomUUID() + prefix;
            product.setImgs(newName);
            //确定路径
            String path = "F://picture//";
            //修改存储路径
            pic.transferTo(new File(path, newName));
        }
        if (!productService.updateById(product))
            return AjaxResult.error("修改失败!");
        return AjaxResult.success("修改成功!");
    }

    @RequestMapping("/upInuse")
    @ResponseBody
    //修改状态
    public AjaxResult updateIunse(@RequestParam("prostr") String prostr, @RequestParam("state") int state) {
        // System.out.println("传过来的参数为:" + prostr);
        String[] str = prostr.split("-");
//        for (String s : str) {
//            System.out.println("循环值为:" + s);
//        }
        List<Product> list = new ArrayList<>();

        for (String s : str) {
            Product product = productService.getById(Integer.parseInt(s));
            if (state == 1) {
                product.setInuse(true);
            } else if (state == 0) {
                product.setInuse(false);
            }
            list.add(product);
        }
        productService.updateBatchById(list);
        return AjaxResult.success("修改完成!");
    }

    @RequestMapping("/goPurchase")
    //查找单个
    public String goPurchase(@RequestParam("id") long id, @RequestParam("userId") long userId, Model model) {
        //传商品
        Product product = productService.getById(id);
        model.addAttribute("p", product);
        //传该用户所拥有的地址
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("userid", userId);
        List<Address> addList = addressService.list(wrapper);
        model.addAttribute("ad", addList);
        model.addAttribute("user", userId);
        return "kProduct/Purchase";
    }
}

